﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dao;

namespace Web.Page
{
    public partial class PermissionAssign : System.Web.UI.Page
    {
        protected string id;
        protected Guid guid;
        protected string name;
        protected List<RolePermission> rolePermissions;
        protected string resultMessage = "";
        RolePermissions_Dao dao = new RolePermissions_Dao();

        protected void Page_Load(object sender, EventArgs e)
        {
            id = Request.QueryString["id"];
            guid = Guid.Parse(id);
            name = Request.QueryString["name"];

            if (name != null)
            {
                this.lbTitle.Text = "分配权限到角色：" + name;
            }
            else
            {
                this.lbTitle.Text = "分配权限到角色";
            }

            if (!IsPostBack)
            {
                BindGridview();
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string pid = GridView1.DataKeys[e.Row.RowIndex].Value.ToString().Trim();
                CheckBox cb = e.Row.FindControl("cbAssign") as CheckBox;
                cb.Checked = RoleHasPermisison(pid);
                cb.Attributes.Add("id", pid);
            }
        }

        private bool RoleHasPermisison(string permisisonId)
        {
            foreach (var rp in rolePermissions)
            {
                if (rp.PermissionId.ToString().Equals(permisisonId))
                {
                    return true;
                }
            }

            return false;
        }

        private void BindGridview()
        {
            rolePermissions = dao.GetByRole(id);
            List<Permission> list = new Permissions_Dao().QueryAll();
            this.GridView1.DataSource = list;
            this.GridView1.DataBind();
        }

        protected void cbAssign_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (sender as CheckBox);
            string pid = cb.Attributes["id"];
            int res = 0;
            if (cb.Checked)
            {
                RolePermission rp = new RolePermission();
                rp.PermissionId = Guid.Parse(pid);
                rp.RoleId = Guid.Parse(id);
                res = dao.Add(rp);
            }
            else
            {
                res = dao.Delete(id, pid);
            }

            if (res == 1)
            {
                resultMessage = "更新角色的权限成功。";
            }
            else
            {
                resultMessage = "更新角色的权限失败。";
            }

            lbResult.Text = resultMessage;
            BindGridview();
        }
    }
}